<template>
  <div class="app-container">
    <el-card class="search-from" ref="searchRef">
      <el-form
        :inline="true"
        class="form-inline"
        :model="searchfilter"
        ref="searchFormRef"
        label-width="70"
      >
        <el-row>
          <template v-for="(item, index) in formItem">
            <el-col :span="6">
              <!-- 
     用validate或者 reset，
     一定要加prop参数
       -->
              <el-form-item
                :label="item.label"
                v-show="hasFolder(index)"
                :prop="item.field"
              >
                <template v-if="item.field == 'hasException'">
                  <el-select
                    v-model="searchfilter[item.field]"
                    :style="{ width: '100%' }"
                    :key="index"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in exceptionOption"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>

                <template v-else-if="item.field == 'httpMethod'">
                  <el-select
                    v-model="searchfilter[item.field]"
                    :style="{ width: '100%' }"
                    :key="index"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in httpMethodOption"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
                <template v-else-if="item.field == 'httpStatusCode'">
                  <el-select
                    v-model="searchfilter[item.field]"
                    :style="{ width: '100%' }"
                    :key="index"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in httpStatusCodeOption"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </template>
                <template v-else-if="item.field == 'timeRange'">
                  <el-date-picker
                    v-model="searchfilter[item.field]"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </template>
                <template v-else>
                  <el-input v-model="searchfilter[item.field]"></el-input>
                </template>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <el-row>
        <el-col :span="6" :offset="18">
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="searchLog">查询</el-button>
            <el-button type="primary" :icon="Search" @click="reset(searchFormRef)"
              >重置</el-button
            >
            <el-button link :icon="ArrowUp" v-if="!isFold" @click="isFold = !isFold"
              >收起</el-button
            >
            <el-button link :icon="ArrowDown" v-else @click="isFold = !isFold"
              >展开</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="list">
      <div class="list-table">
        <el-table style="width: 100%; height: 100%" :data="auditList?.items">
          <el-table-column
            type="index"
            width="100"
            label="#"
            align="center"
          ></el-table-column>

          <template v-for="(item, index) in columns">
            <el-table-column
              :width="item.width"
              v-if="item.isL18"
              :prop="item.field"
              :label="i18n.global.t(item.label)"
            >
              <template #default="scope" v-if="item.format">
                {{ moment(scope.row.field).format(item.format) }}
              </template>
            </el-table-column>
            <template v-else>
              <el-table-column
                :width="item.width"
                v-if="item.field == 'httpStatusCode'"
                :prop="item.field"
                :label="item.label"
              >
                <template #default="scope">
                  <el-tag :type="requestStatusCode(scope.row.httpStatusCode)">
                    {{ scope.row.httpStatusCode }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column
                :width="item.width"
                v-else-if="item.field == 'executionDuration'"
                :prop="item.field"
                :label="item.label"
              >
                <template #default="scope">
                  <el-tag
                    effect="dark"
                    :type="requestDuration(scope.row.executionDuration)"
                  >
                    {{ scope.row.executionDuration }}ms
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                :width="item.width"
                v-else-if="item.field == 'httpMethod'"
                :prop="item.field"
                :label="item.label"
              >
                <template #default="scope">
                  <el-tag :type="requestMethod(scope.row.httpMethod)">
                    {{ scope.row.httpMethod }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column
                :width="item.width"
                v-else
                :prop="item.field"
                :label="item.label"
              >
              </el-table-column>
            </template>
          </template>
          <el-table-column label="操作" align="center" fixed="right" width="150">
            <template #default="scope">
              <el-button text type="primary" @click="showDetail(scope.row.id)"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="Number(tablePage.totalResult)"
          :page-size="tablePage.pageSize"
          @change="handlePageChange"
          v-model:current-page="tablePage.currentPage"
        />
      </div>
    </el-card>

    <detail
      :audit-Id="auditId"
      v-if="detailVisable"
      @closedialogevent="(data:boolean)=>{
      detailVisable=data;
      
    }"
    />
  </div>
</template>
<script setup lang="ts">
import moment from "moment";
import AppContainer from "@/components/AppContainer/index.vue";
import i18n from "@/lang/index";
import { getAuditLogs } from "@/api/identity/logs/auditlog/index";
import { Search, ArrowUp, ArrowDown } from "@element-plus/icons-vue";
import { FormInstance } from "element-plus";
import detail from "./detail.vue";
const searchfilter = ref<object>({
  url: null,
  httpMethod: null,
  userName: null,
  applicationName: null,
  hasException: null,
  startTime: null,
  httpStatusCode: null,
  timeRange: null,
});
let searchFormRef = ref<FormInstance>();
const isFold = ref<boolean>(false);
const formItem = [
  {
    label: "请求地址",
    field: "url",
  },
  {
    label: "请求方法",
    field: "httpMethod",
  },
  {
    label: "用户名称",
    field: "userName",
  },
  {
    label: "应用名称",
    field: "applicationName",
  },
  {
    label: "日期",
    field: "timeRange",
  },
  {
    label: "是否异常",
    field: "hasException",
  },
  {
    label: "状态码",
    field: "httpStatusCode",
  },
];
const httpMethodOption = [
  {
    label: "获取(GET)",
    value: "GET",
  },
  {
    label: "修改(PUT)",
    value: "PUT",
  },
  {
    label: "提交(POST)",
    value: "POST",
  },
  {
    label: "删除(DELETE)",
    value: "DELETE",
  },
];
const exceptionOption = [
  {
    label: "是",
    value: true,
  },
  {
    label: "否",
    value: false,
  },
];
const httpStatusCodeOption = [
  {
    label: "成功(200)",
    value: 200,
  },
  {
    label: "未登录(401)",
    value: 401,
  },
  {
    label: "未授权(403)",
    value: 403,
  },
  {
    label: "未找到资源(404)",
    value: 404,
  },
  {
    label: "异常(500)",
    value: 500,
  },
];

const columns = [
  {
    label: "状态码",
    field: "httpStatusCode",
    width: 130,
  },
  {
    label: "请求方法",
    field: "httpMethod",
    width: 140,
  },
  {
    label: "耗时(毫秒)",
    field: "executionDuration",
    width: 130,
  },
  {
    label: "请求地址",
    field: "url",
    width: 220,
  },
  {
    label: "AbpAuditLogging['UserName']",
    field: "userName",
    width: 140,
    isL18: true,
  },
  {
    label: "AbpAuditLogging['TenantName']",
    field: "tenantName",
    width: 160,
    isL18: true,
  },
  {
    label: "AbpAuditLogging['ExecutionTime']",
    field: "executionTime",
    width: 160,
    isL18: true,
    format: "YYYY-MM-DD HH:mm:ss",
  },
  {
    label: "AbpAuditLogging['ApplicationName']",
    field: "applicationName",
    width: 140,
    isL18: true,
  },
  {
    label: "AbpAuditLogging['ClientIpAddress']",
    field: "clientIpAddress",
    width: 140,
    isL18: true,
  },
];
const tablePage = ref<any>({
  currentPage: 1,
  pageSize: 10,
  totalResult: 0,
});
const detailVisable = ref<boolean>(false);
const auditList = ref<any>({});
const auditId = ref<string>("");

const hasFolder = (index: number) => {
  //console.log("index", index);
  if (index < 4) {
    return true;
  } else {
    return !isFold.value;
  }
};
const getAuditList = async () => {
  let param = { ...searchfilter.value };
  param.skipCount = (tablePage.value.currentPage - 1) * tablePage.value.pageSize;
  param.maxResultCount = tablePage.value.pageSize;
  if (param.timeRange != null && param.timeRange.length > 0) {
    param.startTime = `${param.timeRange[0]} 00:00:00`;
    param.endTime = `${param.timeRange[1]} 23:59:59`;
  }
  auditList.value = await getAuditLogs(param);
  tablePage.value.totalResult = auditList.value.totalCount;
};
const handlePageChange = (currentPage: number, pageSize: number) => {
  tablePage.value.currentPage = currentPage;
  getAuditList();
};
const searchLog = () => {
  tablePage.value.currentPage = 1;
  getAuditList();
};
const requestDuration = (duration: number) => {
  let type = "success";
  if (duration > 2 * 1000) {
    type = "warning";
  } else if (duration > 5 * 1000) {
    type = "error";
  }
  return type;
};

const requestStatusCode = (code: number) => {
  let type = "success";
  switch (code) {
    case 401:
    case 403:
    case 404:
      type = "warning";
      break;
    case 500:
      type = "danger";
      break;
  }
  return type;
};
const requestMethod = (method: String) => {
  let type = "success";
  switch (method.toUpperCase()) {
    case "GET":
      type = "info";
      break;
    case "PUT":
      type = "warning";
      break;
    case "POST":
      type = "success";
      break;
    case "DELETE":
      type = "danger";
      break;
    default:
      type = "info";
  }
  return type;
};
const reset = (formEl: FormInstance | any) => {
  if (!formEl) return;
  formEl.resetFields();
};

const showDetail = (id: string) => {
  detailVisable.value = true;
  auditId.value = "";
  auditId.value = id;
};

onMounted(() => {
  getAuditList();
});
</script>
<style scoped type="sass">
:deep(.eselect) {
  width: 100% !important;
  min-width: 100px;
  display: block;
}

.el-form--inline .el-form-item {
  display: flex;
  justify-content: space-between;
}
.el-row {
  width: 100%;
}

.search-from {
  width: 100%;
}
</style>
